function validateNumber(num) {
    var phoneNumberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;  
    if (phoneNumberPattern.test(num.value)) {
        return true;
    }
    sswAlert('ssw_dime',"Phone number is invalid: "+ num.value);
    return false;
} 

function validateForm(formName) {
    var f = document.forms[formName];
    if (formName == 'register') {
        var email = f['username'].value;
        var atpos = email.indexOf("@");
        var atdot = email.lastIndexOf(".");
        if (atpos < 1 || atdot < atpos+2 || atdot+2>=email.length) {
            sswAlert('ssw_dime',"Username must be a valid email address: "+ email);
            return false;
        }
        return true;
    }
    if (formName == 'userinfo') {
        return (
            validateNumber(f['_homephone']) && 
            validateNumber(f['_workphone']) && 
            validateNumber(f['_cellphone'])
        );
    }
    return true;
}

function disableForm() {
    $('form').find('input, button, textarea, select').attr('disabled','disabled');
}

function enableForm() {
    $('form').find('input, button, textarea, select').removeAttr('disabled');
}

function buildStringFromFields(list,table,keys) {
    var y = '';
    if (table) {
        y += "<p><table>";
    }
    y += buildRowsStringFromFields(list,table,keys);
    if (table) {
        y += '</table></p>';
    }
    return y;
}

function buildRowsStringFromFields(list,table,keys) {
    y = '';
    var tr1 = '';
    var td1 = '';
    var tr0 = '';
    var td0 = '';
    if (table) {
        tr1 += '<tr>';
        td1 += '<td style="border:solid 1px green;">';
        tr0 += '</tr>';
        td0 += '</td>';// style="border:solid 1px green;">';
    }
    for (var i in list) {        
        y += tr1 + td1;
        var e = list[i];
        if (e == null) {
            e = "?";
        }        
        if (keys) {
            y += i + td0 + td1;
        }
        y += e;
        y += td0 + tr0;
    }
    return y;
}

function showNamesAsSelect(obj1,obj2,list,add) {
    return showAllAsSelect(obj1,obj2,list,add,"_name");
}

function showAllAsSelect(obj1,obj2,list,add,which) {
    var all = (which == "");
    var y = "<select XXmultiple=no size=12 class=ssw_itemList >";
    if (add) {
        y += "<option>";
        y += "-------new-entry-------";
        y += "</option>";
    }
    var full = {}
    var disps = {}
    for (var i in list) {
        var line = list[i];
        y += "<option>";
        var fl = buildStringFromFields(line,false,false);
        var nm = line[which];
        full[nm] = buildStringFromFields(line,true,true);
        disps[nm] = line['_display'];
        if (all) {
            y += fl;
        } else {
            y += nm;
        }
        y += "</option>";
    }
    y += "</select>";
    $(obj1).html(y);
    //listen(obj2,full);
    listen2(obj2,disps);
}

function listEntities(typ,view) {
    var obj1 = '.ssw_entityBlock#1';
    var obj2 = '.ssw_entityBlock#2';
    getEntitiesFromServer(typ,obj1,obj2,showNamesAsSelect,view);
}

function setSessionAttr(k, v) {
    // Need sync call here because the whole point is to 
    // side-effect the session. 
    var r = false; 
    $.ajax({ 
         async: false, 
         url: "Ajx?op=sessattr&key="+k+"&val="+v+"", 
         dataType: "json", 
         success: function(data) {
             if (data == true) {                   
                 r = true; 
             }
         }
    });
    return r; 
    //$.getJSON("Ajx?", {op:"sessattr", key:k, val:v}, function() {
    //});
}

function getEntitiesFromServer(typ,obj1,obj2,handler,view) {
    var list = [];
    $.getJSON("Ajx?", {op:view, type:typ}, function(data) {
        for(i=0; i<data.length; i++) {
            e = data[i];
            s = $.param(e);
            var line = {};
            $.each(e, function(i, val) {
                if (val == null) {
                    val = " ";
                }
                line[i] = val;
            });            
            list.push(line);
        }

        var yb = "<p><table>";
        var keys = "";//<tr><td style='bakground-color:#dde; width:400px;border:solid 1px #dde;'> &nbsp;</td></tr>";
        var vals = "<tr><td style='XXXwidth:400px;XXXborder:solid 1px green;'> &nbsp;</td></tr>";
        var ye = "</table></p>";
            
        $(obj2).html(yb + keys + vals + ye);
        handler(obj1,obj2,list,true,"");        
    });
    return list;
}

function menuTitle(index) {
    switch(index) {
        case 0:
            return "Team";
        case 1:
            return "Field";
        case 2:
            return "Day";
        case 3:
            return "Time";
        default:
            return "??";
    }
}

function listen2(obj2, disps) {
    $('body').on("change", ".ssw_itemList", function() {
        var ent = disps[$(this).val()];
        var y = '<p>'+ ent +'</p>';
        $(obj2).html(y);
        //
        // XXX disableForm();
    });
}

function sswAlert(elm,text) {
    $("#"+elm).html('<div id="'+elm+'" ><p><span XXclass="ui-icon ui-icon-circle-check" style="float: left; margin: 0 7px 50px 0;"></span></p><p id="'+elm+'_text">Some text</p></div>');
    $("#"+elm+"_text").html(text);
    $("#"+elm).dialog({
        autoOpen: true,
        modal: true,
        title: "Attention!",
        buttons: {
            Close: function() {
                $( this ).dialog("close");
            }
        }
    });
    return false;
}
